/// Author: Samle
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:memorize_words/db/db_serializer.dart';
import 'dart:convert' as convert;
import '../../../../api/words_api.dart';
import '../../../../store/setting_store.dart';
import '../../../routes/app_pages.dart'; /// lib/app/routes/app_pages.dart
import '../../../../db/db_helper.dart';
import '../../../../store/page_store.dart';

class BooksController extends GetxController with StateMixin<List> {
  RxList booksList = [].obs;
  RxInt itemslong = 1.obs;
  RxInt itemsInedx = 0.obs;
  RxInt bookSelected = 0.obs;
  RxInt wordSelected = 0.obs;

  GlobalKey<FormState> booksKey = GlobalKey<FormState>();
  TextEditingController search = TextEditingController();
  /// 引入状态管理
  PageStore _pageStore = PageStore();
  SettingStore _settingStore = SettingStore();
  /// 获取缓存数据
  getStoreData() async {
    paramsForm = await _pageStore.getBooksParamsForm();
    dataForm = await _pageStore.getBooksDataForm();
    bookSelected.value = await _settingStore.getBookSelected();
    wordSelected.value = await _settingStore.getWordSelected();
    print(bookSelected.value);
  }

  /// 查询参数集
  Map paramsForm = {
    "pageSize": 10,
    "pageNum": 1,
    "search" : null,
    "id": null,
    "name": null,
    "content": null,
    "source": null,
  };
  reStr(String oldStr){
    String newStr = oldStr.replaceAll("'", "''");
    return newStr;
  }
  /// 获取 Books 数据集
  getBooksList() async {
    /// 传入查询参数 <其他参数按需传入>
    paramsForm["search"] = reStr(search.text);
    paramsForm["pageSize"] = 10;
    paramsForm["pageNum"] = 1;
    /// 将查询参数集存储到状态管理中
    await _pageStore.setBooksParamsForm(paramsForm);
    /// 进行查询
    booksList.value = await localData.getBooksBySearch(paramsForm);
    change(booksList, status: RxStatus.success());

    // booksList.value = await localData.getBooks();
    // change(booksList, status: RxStatus.success());
  }

  /// 获取 Books 数据集分页
  Future<void> getBooksListMore() async {
    paramsForm["search"] = reStr(search.text);
    paramsForm["pageSize"] = 10;
    paramsForm["pageNum"] = paramsForm["pageNum"] + 1;
    /// 进行查询
    var moreValue = await localData.getBooksBySearch(paramsForm);
    if (moreValue.isNotEmpty) {
      booksList.value.addAll(moreValue);
      change(booksList, status: RxStatus.success());
    } else {
      if (paramsForm["pageNum"] > 1) {
        paramsForm["pageNum"] = paramsForm["pageNum"] - 1;
      }
      Fluttertoast.showToast(
        msg: "已经到底了！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.black12,
        textColor: Colors.black54,
        fontSize: 16.0,
      );
    }
  }

  /// 数据表单
  Map dataForm = {
    "id": null,
    "name": null,
    "path": null,
    "cover": null,
    "num": null,
    "content": null,
    "source": null,
  };

  /// 跳转编辑界面 按需要修改路由
  toEditPage() {
    Get.toNamed('/edit-books', arguments: dataForm)?.then((value) async {
      if (value == null) { return; } else {
        if (value.containsKey("id") && value['id'] != null && value['id'] != ''){
          dataForm = value;
          updateBooks();
        } else {
          dataForm = value;
          addBooks();
        }
      }
    });
  }

  /// 修改 Books 实例
  updateBooks() async {
    /// 更新 dataForm 数据
    /// dataForm = newDataForm;
    /// 将表单数据存储到状态管理中
    await _pageStore.setBooksDataForm(dataForm);
    try {
      var result = await localData.updateBooks(dataForm);
      /// Get.back(result: true); // 更新成功后回调
      dataForm = cleanDataForm;
      await _pageStore.setBooksDataForm(dataForm);
      Fluttertoast.showToast(
        msg: "更新成功！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      onInit();
    } catch (e) {
      /// 更新失败后回调
      Fluttertoast.showToast(
        msg: "更新失败！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }

  /// 新增 Books 实例
  addBooks() async {
    /// 更新 dataForm 数据
    /// dataForm = newDataForm;
    /// 将表单数据存储到状态管理中
    await _pageStore.setBooksDataForm(dataForm);
    try {
      var result = await localData.addBooks(dataForm);
      /// Get.back(result: true); // 新增成功后回调
      dataForm = cleanDataForm;
      await _pageStore.setBooksDataForm(dataForm);
      Fluttertoast.showToast(
        msg: "新增成功！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      onInit();
    } catch (e) {
      /// 新增失败后回调
      Fluttertoast.showToast(
        msg: "新增失败！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }

  /// 数据表单
  Map cleanDataForm = {
    "id": null,
    "name": null,
    "path": null,
    "cover": null,
    "num": null,
    "content": null,
    "source": null,
  };

  /// 删除 Books 实例
  delBooks(form) async {
    if (form.containsKey("id") && form["id"] != ""){
      try {
        var result = await localData.deleteBooks(form["id"]);
        /// Get.back(result: true); // 删除成功后回调
        Fluttertoast.showToast(
          msg: "删除成功！",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.green,
          textColor: Colors.white,
          fontSize: 16.0,
        );
        onInit();
      } catch (e) {
        /// 删除失败后回调
        Fluttertoast.showToast(
          msg: "删除失败！",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0,
        );
      }
    }
  }

  setWordForm(data){
    Map wordForm = {
      "id": null,
      "name": null,
      "trans": null,
      "ukphone": null,
      "ukspeech": null,
      "usphone": null,
      "usspeech": null,
      "syno": null,
      "relWord": null,
      "sentence": null,
      "phrase": null,
      "exam": null,
      "belong": null,
      "checkTimes": null,
      "errorTimes": null,
      "helpText": null,
      "soundText": null,
    };
    wordForm['name'] = data['name']??'';
    wordForm['trans'] = data['trans']??'';
    wordForm['ukphone'] = data['ukphone']??'';
    wordForm['ukspeech'] = data['ukspeech']??'';
    wordForm['usphone'] = data['usphone']??'';
    wordForm['usspeech'] = data['usspeech']??'';
    wordForm['syno'] = data['syno']??'';
    wordForm['relWord'] = data['relWord']??'';
    wordForm['sentence'] = data['sentence']??'';
    wordForm['phrase'] = data['phrase']??'';
    wordForm['exam'] = data['exam']??'';
    wordForm['belong'] = data['belong']??'';
    wordForm['helpText'] = data['helpText']??'';
    wordForm['soundText'] = data['soundText']??'';
    wordForm['checkTimes'] = data['checkTimes']??0;
    wordForm['errorTimes'] = data['errorTimes']??0;
    return wordForm;
  }


  _showCircularDialog(String content) {
    return showDialog(
      barrierDismissible: false,
      context: Get.context!,
      builder: (context) => AlertDialog(
        content: Container(
          height: 100,
          child: Column(
            children: <Widget>[
              CupertinoActivityIndicator(radius: 30),
              SizedBox(height: 10.0),
              Text(content),
            ],
          ),
        ),
      ),
    );
  }
  /// 获取词汇
  getWords(String url,int bookId) async {
    /// 获取词汇列表
    _showCircularDialog("获取中……");
    var words = await WordsApi.getWords(url);
    Get.back();
    itemslong.value = words.length;
    /// 遍历词汇列表
    // words.forEach((word) async {
    for (int i = 0; i < words.length; i++)  {
      itemsInedx.value = i;
      var word = words[i];
      /// 判断单词是否已经记录
      var hasWord = await localData.hasWords(word['headWord']);
      /// 如果已经记录
      if (hasWord.isNotEmpty && hasWord != null && hasWord != {}) {
        print("has - $i");
        /// 判断单词是否记录在当前词典下
        if (!hasWord['belong'].contains(',' + bookId.toString() + ',')){
          /// 如果单词未被记录在当前词典下，则更新记录
          var newWord = json.decode(json.encode(hasWord));
          if (hasWord['belong']=='' || hasWord['belong']==null){
            newWord['belong'] = ',' + bookId.toString() + ',';
          } else {
            newWord['belong'] = newWord['belong'] + bookId.toString() + ',';
          }
          newWord['name'] = reStr(newWord['name']);
          newWord['ukphone'] = reStr(newWord['ukphone']);
          newWord['usphone'] = reStr(newWord['usphone']);
          newWord['trans'] = reStr(newWord['trans']);
          newWord['syno'] = reStr(newWord['syno']);
          newWord['relWord'] = reStr(newWord['relWord']);

          if (newWord['sentence'] == null || newWord['sentence'] == '') {
            newWord['sentence'] = (word['content']['word']['content']['sentence'] != null && word['content']['word']['content']['sentence'] != '') ? json.encode(word['content']['word']['content']['sentence']):'';
          } else {
            Map sentence = json.decode(newWord['sentence']);
            if (sentence.containsKey('sentences') && sentence['sentences'].length == 0){
              newWord['sentence'] = (word['content']['word']['content']['sentence'] != null && word['content']['word']['content']['sentence'] != '') ? json.encode(word['content']['word']['content']['sentence']):'';
            }
          }
          newWord['sentence'] = reStr(newWord['sentence']);
          newWord['phrase'] = reStr(newWord['phrase']);
          newWord['exam'] = reStr(newWord['exam']);

          Map helpText = json.decode(newWord['helpText']);
          if (helpText['default']['val'] == ''){
            helpText['default'] = (word['content']['word']['content']['remMethod'] != null && word['content']['word']['content']['remMethod'] != '' ) ? word['content']['word']['content']['remMethod'] : {"val": "","desc": ""};
          }
          newWord['helpText'] = reStr(json.encode(helpText));
          // newWord['helpText'] = reStr(newWord['helpText']);
          newWord['soundText'] = reStr(newWord['soundText']);
          print(newWord);
          print("updateRes - $i - ${newWord['belong']}");
          var updateRes = await localData.updateWords(newWord);
        }
      } else {
        print("unHas - $i");
        /// 记录该单词
        var newWord = {};
        newWord['name'] = word['headWord']??'';
        newWord['ukphone'] = word['content']['word']['content']['ukphone']??'';
        newWord['ukspeech'] = word['content']['word']['content']['ukspeech']??'';
        newWord['usphone'] = word['content']['word']['content']['usphone']??'';
        newWord['usspeech'] = word['content']['word']['content']['usspeech']??'';
        newWord['trans'] = (word['content']['word']['content']['trans'] != null && word['content']['word']['content']['trans'] != '') ? json.encode(word['content']['word']['content']['trans']):'';
        newWord['syno'] = (word['content']['word']['content']['syno'] != null && word['content']['word']['content']['syno'] != '') ? json.encode(word['content']['word']['content']['syno']):'';
        newWord['relWord'] = (word['content']['word']['content']['relWord'] != null && word['content']['word']['content']['relWord'] != '') ? json.encode(word['content']['word']['content']['relWord']):'';
        newWord['sentence'] = (word['content']['word']['content']['sentence'] != null && word['content']['word']['content']['sentence'] != '') ? json.encode(word['content']['word']['content']['sentence']):'';
        newWord['phrase'] = (word['content']['word']['content']['phrase'] != null && word['content']['word']['content']['phrase'] != '') ? json.encode(word['content']['word']['content']['phrase']):'';
        newWord['exam'] = (word['content']['word']['content']['exam'] != null && word['content']['word']['content']['exam'] != '') ? json.encode(word['content']['word']['content']['exam']):'';
        var helpJson = {
          'default': (word['content']['word']['content']['remMethod'] != null && word['content']['word']['content']['remMethod'] != '' ) ? word['content']['word']['content']['remMethod'] : {"val": "","desc": ""},
          'self': []
        };
        newWord['helpText'] = json.encode(helpJson);
        newWord['belong'] = ',' + bookId.toString() + ',';
        Map newWordForm = setWordForm(newWord);
        var result = await localData.addWords(newWordForm);
      }
    };
    Map newBook_ = await localData.getBooksById(bookId);
    Map newBook = json.decode(json.encode(newBook_));
    newBook['num'] = words.length;
    await localData.updateBooks(newBook);
    // });
  }

  @override
  Future<void> onInit() async {

    await getStoreData();
    await getBooksList();
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }
}
